package com.emily.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.ONews;
import com.emily.test.service.ONewsService;
import com.emily.test.service.RedisService;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "oNews")
@Api(value = "ONewsApi", description = "ONews接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class ONewsController {
    private Logger logger = LoggerFactory.getLogger(ONewsController.class);

    @Autowired
    private ONewsService oNewsService;

    @Autowired
    private RedisService redisService;

    /**
     * 根据条件查询新闻列表
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value="根据查询条件获取新闻信息", notes="根据查询条件获取新闻信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "新闻ID"),
            @ApiImplicitParam(name = "title", value = "新闻标题"),
            @ApiImplicitParam(name = "content", value = "新闻内容"),
            @ApiImplicitParam(name = "isChecked", value = "是否审核通过"),
            @ApiImplicitParam(name = "editorId", value = "作者ID"),
            @ApiImplicitParam(name = "editorName", value = "作者姓名"),
            @ApiImplicitParam(name = "updateTime", value = "修改时间"),
            @ApiImplicitParam(name = "url", value = "新闻链接地址"),
            @ApiImplicitParam(name = "companyCode", value = "公司code"),
            @ApiImplicitParam(name = "state", value = "启用状态")
    })
    @PostMapping(value = "selectNewsListByCondition")
    public ResponseResult selectNewsListByCondition(@RequestBody(required = false) JSONObject jsonObject, HttpServletRequest request) throws Exception {
        ONews oNews= (ONews) ConstentUtil.json2Object(jsonObject, ONews.class);
        String token = request.getHeader("token");
        Map<String,Object> userMap= (Map<String, Object>) redisService.get(token);
        String companyCode=null;
        if(!ConstentUtil.isEmpty(jsonObject)){
            if(!ConstentUtil.isEmpty(jsonObject.getString("companyCode"))){
                companyCode=jsonObject.getString("companyCode");
            }
        }
        if(!ConstentUtil.isEmpty(userMap)){
            if(!ConstentUtil.isEmpty(userMap.get("companyCode"))){
                companyCode= userMap.get("companyCode") == null ? null : (String) userMap.get("companyCode");
            }
        }
//        String companyCode= userMap.get("companyCode") == null ? null : (String)userMap.get("companyCode");
        oNews.setCompanyCode(companyCode);
        try {
            List<ONews> oNewsList=oNewsService.selectNewsListByCondition(oNews);
            logger.info("根据查询条件获取新闻信息成功:{}",oNewsList);
            return ResponseResult.success(oNewsList);
        } catch (Exception e) {
            logger.info("根据查询条件获取新闻信息异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }


    /**
     * 根据条件查询几条最新新闻
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value="根据条件查询几条新闻", notes="根据条件查询几条新闻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "新闻ID"),
            @ApiImplicitParam(name = "title", value = "新闻标题"),
            @ApiImplicitParam(name = "content", value = "新闻内容"),
            @ApiImplicitParam(name = "isChecked", value = "是否审核通过"),
            @ApiImplicitParam(name = "editorId", value = "作者ID"),
            @ApiImplicitParam(name = "editorName", value = "作者姓名"),
            @ApiImplicitParam(name = "updateTime", value = "修改时间"),
            @ApiImplicitParam(name = "url", value = "新闻链接地址"),
            @ApiImplicitParam(name = "companyCode", value = "公司code"),
            @ApiImplicitParam(name = "total", value = "新闻条数"),
            @ApiImplicitParam(name = "state", value = "启用状态")
    })
    @PostMapping(value = "selectSomeNewNewsListByCondition")
    public ResponseResult selectSomeNewNewsListByCondition(@RequestBody(required = false) JSONObject jsonObject, HttpServletRequest request) throws Exception {
        ONews oNews= (ONews) ConstentUtil.json2Object(jsonObject, ONews.class);

        String token = request.getHeader("token");
        Map<String,Object> userMap= (Map<String, Object>) redisService.get(token);
        String companyCode=null;
        //需要查询最新的条数
        Integer total=null;
        if(!ConstentUtil.isEmpty(jsonObject)){
            total=jsonObject.getInteger("total");
            if(!ConstentUtil.isEmpty(jsonObject.getString("companyCode"))){
                companyCode=jsonObject.getString("companyCode");
            }
        }
        if(!ConstentUtil.isEmpty(userMap)){
            if(!ConstentUtil.isEmpty(userMap.get("companyCode"))){
                companyCode= userMap.get("companyCode") == null ? null : (String) userMap.get("companyCode");
            }
        }
//        String companyCode= userMap.get("companyCode") == null ? null : (String)userMap.get("companyCode");
        oNews.setCompanyCode(companyCode);
        try {
            List<ONews> oNewsList=oNewsService.selectSomeNewNewsListByCondition(oNews,total);
            logger.info("根据查询条件获取新闻信息成功:{}",oNewsList);
            return ResponseResult.success(oNewsList);
        } catch (Exception e) {
            logger.info("根据查询条件获取新闻信息异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 插入新闻
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value="插入新闻", notes="插入新闻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "新闻ID"),
            @ApiImplicitParam(name = "title", value = "新闻标题",required = true),
            @ApiImplicitParam(name = "content", value = "新闻内容",required = true),
            @ApiImplicitParam(name = "isChecked", value = "是否审核通过"),
            @ApiImplicitParam(name = "editorId", value = "作者ID"),
            @ApiImplicitParam(name = "editorName", value = "作者姓名",required = true),
            @ApiImplicitParam(name = "updateTime", value = "修改时间"),
            @ApiImplicitParam(name = "url", value = "新闻链接地址"),
            @ApiImplicitParam(name = "companyCode", value = "公司code"),
            @ApiImplicitParam(name = "state", value = "启用状态")
    })
    @PostMapping(value = "insertNews")
    public ResponseResult insertNews(@RequestBody JSONObject jsonObject,HttpServletRequest request) throws Exception {
        ONews oNews= (ONews) ConstentUtil.json2Object(jsonObject, ONews.class);
        String token = request.getHeader("token");
        Map<String,Object> userMap= (Map<String, Object>) redisService.get(token);
        String companyCode= userMap.get("companyCode") == null ? null : (String)userMap.get("companyCode");
        oNews.setCompanyCode(companyCode);
        if(!ConstentUtil.isEmpty(oNews)){
            oNews.setUpdateTime(DateUtil.getNowStr());
        }
        try {
            int num =oNewsService.insertNews(oNews);
            logger.info("插入一条新闻成功,插入条数:{}",num);
            return ResponseResult.success(num);
        } catch (Exception e) {
            logger.info("插入一条新闻异常",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }

    /**
     * 修改信息
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value="修改新闻", notes="修改新闻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "新闻ID",required = true),
            @ApiImplicitParam(name = "title", value = "新闻标题"),
            @ApiImplicitParam(name = "content", value = "新闻内容"),
            @ApiImplicitParam(name = "isChecked", value = "是否审核通过"),
            @ApiImplicitParam(name = "editorId", value = "作者ID"),
            @ApiImplicitParam(name = "editorName", value = "作者姓名"),
            @ApiImplicitParam(name = "updateTime", value = "修改时间"),
            @ApiImplicitParam(name = "companyCode", value = "公司code"),
            @ApiImplicitParam(name = "url", value = "新闻链接地址"),
            @ApiImplicitParam(name = "state", value = "启用状态")
    })
    @PostMapping(value = "updateNews")
    public ResponseResult updateNews(@RequestBody JSONObject jsonObject) throws Exception {
        ONews oNews= (ONews) ConstentUtil.json2Object(jsonObject, ONews.class);
        if(ConstentUtil.isEmpty(oNews)){
            return ResponseResult.fail("新闻信息"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        if(ConstentUtil.isEmpty(oNews.getId())){
           return ResponseResult.fail("新闻ID"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        oNews.setUpdateTime(DateUtil.getNowStr());
        try {
            int num =oNewsService.updateNews(oNews);
            logger.info("修改一条新闻成功,修改条数:{}",num);
            return ResponseResult.success(num);
        } catch (Exception e) {
            logger.info("修改一条新闻异常",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 禁用多条新闻
     * @param jsonObject    其中新闻ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="禁用多条新闻", notes="禁用多条新闻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "新闻ids", required = true)
    })
    @PostMapping(value = "disabledNewsById")
    public ResponseResult disabledNewsById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<ONews> oNewsList=new ArrayList<ONews>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                ONews oNews=new ONews();
                oNews.setId(ConstentUtil.strToInteger(idStr[i]));
                oNews.setState(0);
                oNews.setUpdateTime(DateUtil.getNowStr());
                oNewsList.add(oNews);
            }
        }
        try {
            int num=oNewsService.updateNewsListByIds(oNewsList);
            logger.info("ids为{}的新闻已禁用",ids);
            return ResponseResult.success(oNewsList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("禁用失败");
        }
    }

    /**
     * 启用多条新闻
     * @param jsonObject    其中新闻ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="启用多条新闻", notes="启用多条新闻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "新闻ids", required = true)
    })
    @PostMapping(value = "enabledNewsById")
    public ResponseResult enabledNewsById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<ONews> oNewsList=new ArrayList<ONews>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                ONews oNews=new ONews();
                oNews.setId(ConstentUtil.strToInteger(idStr[i]));
                oNews.setState(1);
                oNews.setUpdateTime(DateUtil.getNowStr());
                oNewsList.add(oNews);
            }
        }
        try {
            int num=oNewsService.updateNewsListByIds(oNewsList);
            logger.info("ids为{}的新闻已启用",ids);
            return ResponseResult.success(oNewsList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("启用失败");
        }
    }

    /**
     * 删除多条新闻
     * @param jsonObject    其中新闻ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="删除多条新闻", notes="删除多条新闻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "新闻ids", required = true)
    })
    @PostMapping(value = "deleteNewsById")
    public ResponseResult deleteNewsById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<ONews> oNewsList=new ArrayList<ONews>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                ONews oNews=new ONews();
                oNews.setId(ConstentUtil.strToInteger(idStr[i]));
                oNews.setState(2);
                oNews.setUpdateTime(DateUtil.getNowStr());
                oNewsList.add(oNews);
            }
        }
        try {
            int num=oNewsService.updateNewsListByIds(oNewsList);
            logger.info("ids为{}的新闻已删除",ids);
            return ResponseResult.success(oNewsList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("删除失败");
        }
    }

}
